// 用户信息接口

const express = require('express');
const router = express.Router();
//m密码使用md5模块进行的加密
const md5 = require('md5');
// 引入数据库
const db = require("../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法验证码
const { capOptions, generateToken, verifyToken, getClientIp, toCamelCase, capitalizeFirstLetter } = require("../../config/utils");
// 引入日志
const log = require("../log");


// 获取验证码接口
router.get("/captchaImage", function (req, res) {
    console.log("===========获取验证码接口============");
    const { text, base64String } = capOptions();
    res.send({
        msg: "验证码获取成功",
        code: 200,
        captchaOnOff: true,
        img: base64String,
        uuid: md5(text.toUpperCase()),
    })
})


// 登录接口
router.post("/login", function (req, res) {
    console.log("===========登录接口============");
    const { password, username,uuid,code} = req.body
    if (uuid != md5(code.toUpperCase())) {
        res.send({
            msg: "验证码错误", 
            code: 500
        })
        return
    }
    console.log("===========验证码匹配正确============");

    // 查询数据库
    db.query("查询用户信息表", `select user_name, password from sys_user where user_name = '${username}'`, function (err, results) {
        if (err) {
            res.send({
                msg: "查询用户信息表错误", 
                code: 500
            })
            return
        }
        if (results.length == 0) {
            res.send({
                msg: "用户不存在", 
                code: 500
            })
            return
        }
        if (results[0].password != md5(password)) {
            res.send({
                msg: "密码错误", 
                code: 500
            })
            return
        }

        console.log("===========账号密码匹配正确============");

        if (results[0].password == md5(password)) {
            // 生成token
            const token = generateToken({username, password});
            // // 解析token
            // console.log(verifyToken(token));
            res.send({
                msg: "登录成功", 
                token: token,
                code: 200
            })

            // 更新记录id和登录时间
            const ClientIp = getClientIp(req);
            // 生成时间戳追溯
            const time = moment().format('YYYY-MM-DD HH:mm:ss')
            // 更新数据库
            db.query("更新用户登录信息表", `update sys_user set login_ip = '${ClientIp}', login_date = '${time}' where user_name = '${username}'`, function (err, results) {})
        }

    })

})

// 获取用户详细信息接口
router.get("/getInfo", function (req, res) {
    console.log("===========获取用户详细信息接口============");
    // 解析token
    const { username } = verifyToken(req.headers.authorization);
    // 查询用户表
    db.query("查询用户表", `SELECT * FROM sys_user where user_name = '${username}' `, function (err, result) {
        if (err) {
            res.send({
                msg: "查询用户表失败", 
                code: 500
            })
            return
        }
        if(result.length>0){
            let user = {}
            user = toCamelCase(result[0])
            delete user.password
            // 联合查询，根据用户id查询角色权限id，根据角色id查询角色信息
            let sql_union = `SELECT * FROM sys_user_role a LEFT JOIN sys_role b ON a.role_id = b.role_id where a.user_id = '${user.userId}'`
            db.query("查询用户角色表", sql_union, function (err1, result1) {
                if (err1) {
                    res.send({
                        msg: "查询用户角色表失败", 
                        code: 500
                    })
                    return
                }
                if(result1.length>0){
                    user.roles = toCamelCase(result1[0])
                    user = {...user, ...user.roles}
                    user.admin = user.data_scope == 1 ? true : false
                    
                    // 查询用户权限表
                    // 根据角色id查询角色权限表,再根据权限id查询权限表
                    let sql_menu_union = `SELECT perms FROM sys_role_menu a LEFT JOIN sys_menu b ON a.menu_id = b.menu_id 
                    where a.role_id = '${user.roleId}' and  b.menu_type != 'M' and b.status = '0'`
                    // 判断是否为管理员
                    if(user.roleKey == "admin"){
                        sql_menu_union = `SELECT perms FROM sys_menu where menu_type != 'M' and status = '0'`
                    }
                    console.log(sql_menu_union)
                    db.query("查询用户权限表", sql_menu_union, function (err2, result2) {
                        if (err2) {
                            res.send({
                                msg: "查询用户权限表失败", 
                                code: 500
                            })
                            return
                        }
                        if(result2.length>0){
                            result2 = result2.map(item => item.perms)
                            res.send({
                                msg: "查询成功", 
                                code: 200,
                                user,
                                roles: [user.roleKey],
                                permissions:result2
                            })
                        }
                    })
                }else{
                    res.send({
                        msg: "没有该角色", 
                        code: 400
                    })
                    return
                }
            })
            
        }
    })
})

// 获取路由接口
router.get("/getRouters", function (req, res) {
    console.log("===========获取路由接口============");
    // 解析token
    const { username } = verifyToken(req.headers.authorization);
    // 根据用户名查询用户id，再根据用户id查询用户角色id，再根据角色id查询角色权限表，再根据权限id查询权限表
    let sql_union = `SELECT menu_name, path, component, menu_type, icon  FROM sys_menu where menu_type = 'M' OR menu_type = 'C' and 
        menu_id in (select menu_id from sys_role_menu where role_id = 
        (SELECT b.role_id FROM sys_user a 
        LEFT JOIN sys_user_role b ON a.user_id = b.user_id  
        where a.user_name = '${username}'))`
    // 判断是否为管理员
    if(username == "admin"){
        sql_union = `SELECT menu_name, path, component, menu_type, icon  FROM sys_menu where menu_type = 'M' OR menu_type = 'C'`
    }
    // 查询用户权限表
    db.query("查询用户权限表", sql_union, function (err, result) {
        if (err) {
            res.send({
                msg: "查询用户权限表失败", 
                code: 500
            })
            return
        }
        if(result.length>0){
            // 生成菜单
            let menu = []
            result.forEach(item => {
                if(item.menu_type == 'M'){
                    menu.push({
                        "name": capitalizeFirstLetter(item.path),
                        "path": `/${item.path}`,
                        "hidden": false,
                        "redirect": "noRedirect",
                        "component": "Layout",
                        "alwaysShow": true,
                        "meta": {
                            "title": item.menu_name,
                            "icon": item.icon,
                            "noCache": false,
                            "link": null
                        },
                        children: []
                    })
                }
            })
            result.forEach(item => {
                if(item.menu_type == 'C'){
                    menu.forEach(item1 => {
                        if(item.component.includes(item1.name.toLowerCase())){
                            item1.children.push({
                                "name": capitalizeFirstLetter(item.path),
                                "path": item.path,
                                "hidden": false,
                                "component": item.component,
                                "meta": {
                                    "title": item.menu_name,
                                    "icon": item.icon,
                                    "noCache": false,
                                    "link": null
                                }
                            })
                        }
                    })
                }
            })
            // 判断下拉菜单是否有子菜单
            let nuewMenu = []
            menu.forEach(item => {
                if(item.children.length != 0){
                    nuewMenu.push(item)
                }
            })
            res.send({
                msg: "操作成功", 
                code: 200,
                data: nuewMenu
            })
        }
    })
})

// 退出登录接口
router.post("/logout", function (req, res) {
    console.log("===========退出登录接口============");
    res.send({
        msg: "退出成功", 
        code: 200
    })
})

  
module.exports = router;